package com.xiaolin.security.service;

import com.xiaolin.security.model.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @ClassName MyUserDetailsService
 * @Description 用户校验登录与授权
 * @Detail 自定义用户的另一种方式
 *              授权总结：
 *                  1、角色前缀统一是ROLE_，如果是数据库的角色，要自己在数据库角色前面加上前缀
 *                  2、用户只会在登录时从数据库查询查询角色并授权，如果中途修改了角色权限，可能需要自己再做逻辑处理
 * @Author MyPC
 * @Date 2020/10/8
 * @Version 1.0
 */
@Component
public class MyUserDetailsService implements UserDetailsService{
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    MemberService memberService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1、查询数据库获取用户
        Member member = memberService.selectByName(username);
        if(member==null){
            return null;
        }
        //2、对密码进行加密
        String password = passwordEncoder.encode(member.getPassword());
        // 封装用户权限集合
        List<GrantedAuthority> grantedAuthorities=new ArrayList<>();
        // 从数据库查询用户权限集合
        List<String> roles=memberService.selectRolesByUsername(username);
        if(roles.size()>0){
            for (String role : roles) {
                grantedAuthorities.add(new SimpleGrantedAuthority(role));
            }
        }
        /**
         * String username,  用户名，由用户输入得到
         * String password,  密码，查询数据库得到
         * boolean enabled,  账户是否有效
         * boolean accountNonExpired,  账户是否过期
         * boolean credentialsNonExpired,  凭证是否过期
         * boolean accountNonLocked, 账户是否被锁定，可以从数据库查
         * Collection<? extends GrantedAuthority> authorities
         */
        return new User(username,password,true,true,true,true,grantedAuthorities);
        //        return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}
